package com.star.mall.file.impl;

import cn.hutool.core.io.IoUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.star.mall.base.exception.BusinessException;
import com.star.mall.file.FileService;
import com.star.mall.file.model.IFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.io.OutputStream;

@Service("aliyun")
@Slf4j
@ConditionalOnProperty(
        prefix = "system.file",
        name = {"mode"},
        havingValue = "aliyun",
        matchIfMissing = true
)
public class AliyunOssFileService implements FileService {

    @Value("${system.file.endpoint}")
    private String endpoint;
    @Value("${system.file.accessKeyId}")
    private String accessKeyId;
    @Value("${system.file.accessKeySecret}")
    private String accessKeySecret;
    @Value("${system.file.bucketName}")
    private String bucketName;

    private OSS initClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    @Override
    public void uploadFile(IFile file, InputStream inputStream) {
        saveFile(inputStream, bucketName, file.getName());
        file.setPath(bucketName);
    }

    @Override
    public void saveFile(InputStream inputStream, String resourceLocation, String key) {
        OSS ossClient = initClient();
        try {
            if (!ossClient.doesBucketExist(resourceLocation)) {
                ossClient.createBucket(resourceLocation);
            }
            ossClient.putObject(resourceLocation, key, inputStream);
        }finally {
            ossClient.shutdown();
        }
    }

    @Override
    public void downloadFile(String resourceLocation, String key, OutputStream outputStream) {
        OSS ossClient = initClient();
        try {
            if (!ossClient.doesBucketExist(bucketName)) {
                OSSObject ossObject = ossClient.getObject(bucketName, key);
                InputStream inputStream = ossObject.getObjectContent();
                IoUtil.copy(inputStream, outputStream);
            }else {
                throw new BusinessException("不存在空间"+bucketName);
            }
        }finally {
            ossClient.shutdown();
        }
    }

    @Override
    public boolean deleteFile(String resourceLocation, String key) {
        OSS ossClient = initClient();
        try {
            if (ossClient.doesObjectExist(resourceLocation, key)) {
                ossClient.deleteObject(resourceLocation, key);
                return true;
            }
        }finally {
            ossClient.shutdown();
        }
        return false;
    }

}
